package wifiunion.com.notice.activity;

import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.cloud.media.player.IMediaPlayer;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
import wifiunion.com.notice.BaseActivity;
import wifiunion.com.notice.BaseApplication;
import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.CommonUtils;
import wifiunion.com.notice.ConfigureContact;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.GlideCircleTransform;
import wifiunion.com.notice.HomePageDetailContact;
import wifiunion.com.notice.R;
import wifiunion.com.notice.RecyclerItemClick;
import wifiunion.com.notice.adapter.RollerAdapter;
import wifiunion.com.notice.entity.HomePageConfigure;
import wifiunion.com.notice.entity.LoginMember;
import wifiunion.com.notice.entity.NoticeBackground;
import wifiunion.com.notice.entity.Param;
import wifiunion.com.notice.entity.PushEntity;
import wifiunion.com.notice.entity.User;
import wifiunion.com.notice.fragment.AddFirstScreenFragment;
import wifiunion.com.notice.fragment.NoticeListFragment;
import wifiunion.com.notice.presenter.HomepagePresenter;
import wifiunion.com.notice.presenter.NoticeBackgroundPresenter;
import wifiunion.com.notice.service.AuthtokenIntentService;
import wifiunion.com.notice.service.IntelligenceBackService;
import wifiunion.com.notice.utils.ClickTimeSpanUtil;
import wifiunion.com.notice.utils.PlaySoundUtils;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.utils.db.DBManager;
import wifiunion.com.notice.utils.db.LocNoticeInfo;
import wifiunion.com.notice.utils.glideutils.NewGlideCircleHasBackgroudTransform;
import wifiunion.com.notice.utils.imageprocess.utils.FileUtils;
import wifiunion.com.notice.widget.AboutDialog;
import wifiunion.com.notice.widget.CustomRadioButton;
import wifiunion.com.notice.widget.baiduvideo.BDCloudVideoView;

import static android.text.TextUtils.isEmpty;
import static wifiunion.com.notice.R.id.reight_fl;

/**
 * Created by Administrator on 2016/11/23.
 */

public class HomePageActivity extends BaseActivity implements HomePageDetailContact.MainView, View.OnClickListener, ConfigureContact.NoticeBackgroundView, IMediaPlayer.OnCompletionListener {

    private FrameLayout mContentLayout;


    //设备,用户管理,陌生人管理,系统终端,通知,数据,场所
    private CustomRadioButton mNoticeDataRl, mPlaceDataRl;

    public FragmentManager fragmentManager;


    private NoticeListFragment mNoticeListFragment;


    private AddFirstScreenFragment mAddFirstScreenFragment;


    private RelativeLayout reightView;

    private TranslateAnimation animation;

//    private ImageView mExchangeView;


    private RelativeLayout mCoverLayout;

    private ImageView mCoverHeaderIv/*, mStatusIv, mBottomFirstIv*/;

    private TextView /*mCoverAlphaLeftTv, mCoverAlphaRightTv,*/ mCoverUserNameTv, mCoverContentsTv, mCoverLocNameTv;

//    private RecyclerView mCoverRecycleView;

    TranslateAnimation inAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);

    TranslateAnimation outAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f);


    TranslateAnimation btninAnimation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 1.0f, Animation.RELATIVE_TO_PARENT, 0.0f);

    TranslateAnimation btnoutAnimation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 1.0f);


//    TranslateAnimation messageAnimation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f);


    /*********************
     * 首屏通知相关 开始i
     ***********************************/
    private final int SHOW_COVERLAYOUT_ACTION = 20;
    private final int HIDDERN_COVERLAYOUT_ACTION = 21;

    private final int RECYCLERVIEW_SCOLLER_ACTION = 15;
    private final int REFRESH_COVERLAYOUT_ACTION = 13;
    private final int CLEAR_COVERLAYOUT_ACTION = 14;
    private final int SCROLLER_END_ACTION = 16;

    private ImageView homesettingIv;

    private View tophiddenVV;
    private View topshowVV;

    private View bottomhiddenVV;
    private View bottomshowVV;


    private String mAuthtoken;

    private BaseApplication mIntelCameraApplication;

    //logo
    private ImageView logoIv;
    private TextView sloganTv;
    private User user;


    private ImageView headIv;

    private TextView nameTv;

    private Intent mServiceIntent;

    private PushEntityReceiver receiver = new PushEntityReceiver();
    /**
     * 上按钮，下按钮
     */
//    private Button /*mCoverLayoutUpBtn,*/mCoverLayoutDownBtn;


    private ArrayList<PushEntity> mRealDataList = new ArrayList<>();


    /**
     * recycleview 最多展示item
     */
    private int showNumber = 3;

    /**
     * 是否滑动recycleview
     */
    private boolean flyByFinger = false;

    /**
     * 全局的一个计时器
     */
    private Timer mGlobalTimer;

    /**
     * 当前显示的位置
     */
    private int mGlobalPos = 0;

    private ImageView mainviewTopIv;
    private TextView mainviewTopTv;

    private TextView mainSettingTv;

    private RelativeLayout mRollerRecycleViewRl;

    private RecyclerView mRollerRecycleView;

    private RollerAdapter mRollerAdapter;

    private LinearLayoutManager mLinearLayoutManager;


    /**
     * 播放过声音的位置
     */
    private int playYetPos = 0;

    /**
     * 单条记录的停留时间
     */
    int singleTime = 0;
    /**
     * 多条记录的间隔时间
     */
    int mutipleTime = 0;


    private HomepagePresenter homepagePresenter;

    private HomepagePresenter getUserPresenter;

    private NoticeBackgroundPresenter mNoticeBackgroundPresenter;

    private RelativeLayout allCovRl;
    private LinearLayout defaultCovll;
    private RelativeLayout allVideoRl;
    private PendingIntent pendingIntent;
    private AlarmManager alarmManger;
    //动态申请权限
    private String[] permissonArray = new String[]
            {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE
            };

    private int PERMISSION_REQ = 10000;

    private List<String> mRequestPermission = new ArrayList<String>();
    Handler mHandlerExit = new Handler();


    private BDCloudVideoView mPlayView;

    private String mVideoPath;

    private boolean isRegisterBro;

    private String imageUri = "";


    /**
     * recycleview 滑动监听
     */
    RecyclerView.OnScrollListener mScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

            switch (newState) {
                case RecyclerView.SCROLL_STATE_IDLE:

                    try {
                        int lastpos = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
                        if (playYetPos != lastpos) {
                            PushEntity pe = mRealDataList.get(lastpos);
                            playSoundByType(pe);
                            playYetPos = lastpos;
                        }
                        restartScroll();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case RecyclerView.SCROLL_STATE_DRAGGING:
                    flyByFinger = true;
                    if (mGlobalTimer != null) {
                        mGlobalTimer.cancel();
                        mGlobalTimer = null;
                    }

                    break;
            }

            super.onScrollStateChanged(recyclerView, newState);
        }
    };


    public Handler mExchangeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case SHOW_COVERLAYOUT_ACTION:

                    inAnimation.setDuration(800);
                    inAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
                    btnoutAnimation.setDuration(800);
                    btnoutAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
                    btnoutAnimation.setFillAfter(true);
                    mCoverLayout.startAnimation(inAnimation);
//                    mExchangeView.startAnimation(btnoutAnimation);
                    mCoverLayout.setVisibility(View.VISIBLE);
                    if (mRealDataList.isEmpty()) {
                        mRollerRecycleViewRl.setVisibility(View.GONE);
                    } else {
                        mRollerRecycleViewRl.setVisibility(View.VISIBLE);
                    }

//                    mCoverLayoutUpBtn.setVisibility(View.VISIBLE);
//                    mCoverLayoutDownBtn.setVisibility(View.GONE);
//                    Constants.EXCEPTION_PAGE_VALUE = "0";
//                    SharedPreferencesUtils.setSharedPreferences(Constants.EXCEPTION_PAGE_KEY, "0", getApplicationContext());
                    break;
                case HIDDERN_COVERLAYOUT_ACTION:

                    outAnimation.setDuration(800);
                    outAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
                    btninAnimation.setDuration(800);
                    btninAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
                    btninAnimation.setFillAfter(true);
                    mCoverLayout.startAnimation(outAnimation);
//                    mExchangeView.startAnimation(btninAnimation);
                    mContentLayout.setVisibility(View.VISIBLE);

//                    mCoverLayoutUpBtn.setVisibility(View.GONE);
//                    mCoverLayoutDownBtn.setVisibility(View.VISIBLE);

//                    SharedPreferencesUtils.setSharedPreferences(Constants.EXCEPTION_PAGE_KEY, "1", getApplicationContext());
                    break;


            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//        this.getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);
        setContentView(R.layout.activity_homepage);

        initParam();
        initView();
//        mIntelCameraApplication = (BaseApplication) getApplication();
        user = SharedPreferencesUtils.getUserSharedPreferences(this);
        mAuthtoken = SharedPreferencesUtils.getSharedPreferences(Constants.CONFIG_AUTHTOKEN, this);

        mHandlerExit.postDelayed(new Runnable() {
            @Override
            public void run() {
                startrequestPermission();
            }
        }, 200);


        startService();
        startTask();

//        initView();
//        // 注册广播
//        initDateReceiver();
//        getHomepage();
//        getUser(uuid);
//        startBackService();
//        mExchangeHandler.sendEmptyMessage(SHOW_COVERLAYOUT_ACTION);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void startrequestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : permissonArray) {
                if (PackageManager.PERMISSION_GRANTED != checkPermission(permission, Process.myPid(), Process.myUid())) {
                    mRequestPermission.add(permission);
                }
            }
            if (!mRequestPermission.isEmpty()) {
                requestPermissions(mRequestPermission.toArray(new String[mRequestPermission.size()]), PERMISSION_REQ);
            } else {
                initData();
            }
        } else {
            initData();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        if (requestCode == PERMISSION_REQ) {
            for (int i = 0; i < grantResults.length; i++) {
                for (String one : permissonArray) {
                    if (permissions[i].equals(one) && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        mRequestPermission.remove(one);
                    }
                }
            }
            initData();
        }
    }

    private void initData() {
        // 注册广播
        initDateReceiver();
        getHomepage();
        getUser(uuid);
        mExchangeHandler.sendEmptyMessage(SHOW_COVERLAYOUT_ACTION);
    }


    private void initDateReceiver() {

        IntentFilter intenfilter = new IntentFilter();
        intenfilter.addAction(Constants.PUSH_NOTICE_ACTION);
        intenfilter.addAction(Constants.HOMEPAGE_MENUNEWNOTICE);
        intenfilter.addAction(Constants.RESTART_ACTION);
        registerReceiver(receiver, intenfilter);

        isRegisterBro = true;

    }


    @Override
    public void getUserDetailSuccess(Object data) {
        LoginMember mm = (LoginMember) data;
        User mUser = new User();
        mUser.setName(placeInfoName);
        mUser.setLogo(placeInfoLogo);
        mUser.setMemberName(mm.getName());
        mUser.setComparisonPic(mm.getComparisonPic());
        mUser.setShowPic(mm.getShowPic());
        mUser.setUuid(uuid);
        mUser.setControlTime(controlTime);
        mUser.setCommunityUuid(mm.getCommunityUuid());
//        SharedPreferencesUtils.setUserSharedPreferences(mUser, getApplicationContext());
        SharedPreferencesUtils.setPlaceUserSharedPreferences(mUser, getApplicationContext());
        SharedPreferencesUtils.setUserSharedPreferences(mUser, getApplicationContext());
    }

    @Override
    public void getUserDetailFailed(Object data) {

    }

    @Override
    public void getHomepageSuccess(Object data) {
        Log.i("test", "#####getHomepageSuccess refreshCustomView");
        hp = (HomePageConfigure) data;
        refreshCustomView();
    }

    @Override
    public void getHomepageFailed(Object data) {

    }


    Gson gson = new Gson();

    @Override
    public void getNoticeBackgroundSuccess(Object obj) {
        nb = (NoticeBackground) obj;
//        if(null != nb)
//        {
//            if(nb.getIsNoticeBackgroundConfig() == 0)
//            {
//                mRollerAdapter.setType(0);
//
//            }
//            else
//            {
//                mRollerAdapter.setType(1);
//                //设置透明度
//                mRollerAdapter.setBackGroundColor(Integer.parseInt(nb.getNoticePellucidity()));
//
//                mRollerAdapter.setTextColor(Integer.parseInt(nb.getNoticeFontColor()));
//            }
//        }

    }

    @Override
    public void getNoticeBackgroundFailed(Object obj) {

    }

    @Override
    public void updateNoticeBackgroundSuccess(Object obj) {

    }

    @Override
    public void updateNoticeBackgroundailed(Object obj) {

    }


    @Override
    public void onCompletion(IMediaPlayer iMediaPlayer) {


    }


    /**
     * 时间与网络状态刷新
     *
     * @author furan
     */
    public class PushEntityReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(Constants.PUSH_NOTICE_ACTION)) {
                if (null != intent) {
                    if (!CommonUtils.isNotLockScreen(context)) {
                        CommonUtils.wakeAndUnlock(context);
                    }

                    Bundle bundle = intent.getExtras();
                    String result = bundle.getString("pushEntity");
                    PushEntity pe = null;
                    try {
                        JsonReader reader = new JsonReader(new StringReader(result));
                        reader.setLenient(true);
                        pe = gson.fromJson(reader, PushEntity.class);
                    } catch (JsonIOException e) {
                        e.printStackTrace();
                        pe = null;
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                        pe = null;
                    } catch (Exception e) {
                        e.printStackTrace();
                        pe = null;
                    }
                    if (null == pe) {
                        return;
                    }

                    //解析Json数据的时候抛出MalformedJsonException会出现这种问题，使用上面的解析方式
//                    PushEntity pe = gson.fromJson(result, new TypeToken<PushEntity>() {
//                    }.getType());
                    if (pe.getType() == 1 || pe.getType() == 2) {
                        return;
                    }


                    if (mRealDataList.isEmpty()) {

                        //如果为视频播放，需要暂停声音
                        if (null != hp) {
                            if (hp.getIsIndexConfig() == 2) {
                                pausePaly();
                            }
                        }


                        //这里初始化判断通知界面显示的内容
                        if (null != nb) {
                            if (nb.getIsNoticeBackgroundConfig() == 0) {
                                mRollerAdapter.setType(0);

                                mRollerRecycleViewRl.setBackgroundDrawable(null);
                                mRollerRecycleViewRl.setBackgroundResource(R.drawable.card_recyclerview_bg);
//                                defaultCovll.setVisibility(View.VISIBLE);

                            } else {


                                mRollerAdapter.setType(1);
                                //设置透明度
                                mRollerAdapter.setBackGroundColor(Integer.parseInt(nb.getNoticePellucidity()));

                                mRollerAdapter.setTextColor(Integer.parseInt(nb.getNoticeFontColor()));
//                                String imageUri = "";
//                                if (!TextUtils.isEmpty(Constants.SERVER_PORT)) {
//
//                                    imageUri = "http://" + Constants.SERVER_IP + ":" + Constants.SERVER_PORT + "/";
//                                } else {
//
//                                    imageUri = "http://" + Constants.SERVER_IP + "/";
//                                }


                                Glide.with(HomePageActivity.this).load(imageUri + nb.getNoticeBackground()).into(new SimpleTarget<GlideDrawable>() {
                                    @Override
                                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {

                                        Log.i("text", "######通知背景设置成功");
                                        mRollerRecycleViewRl.setBackgroundDrawable(null);
                                        mRollerRecycleViewRl.setBackgroundResource(0);
                                        mRollerRecycleViewRl.setBackgroundDrawable(resource);

                                    }
                                });
//                                defaultCovll.setVisibility(View.GONE);
                            }
                        }


                        for (int i = 0; i < showNumber - 1; i++) {
                            PushEntity blank = new PushEntity();
                            blank.setAlarmState(3);
                            blank.setMemberUuid("");
                            mRealDataList.add(blank);
                        }

                        mRealDataList.add(pe);

                        mRollerAdapter.notifyDataSetChanged();
                        mGlobalPos = 2;
                        Message msg = mHandler.obtainMessage();
                        msg.obj = 2;
                        msg.what = REFRESH_COVERLAYOUT_ACTION;
                        mHandler.sendMessage(msg);
                    } else {
                        mRealDataList.add(pe);
                        mRollerAdapter.notifyDataSetChanged();
                    }

                    if (mCoverLayout.getVisibility() == View.VISIBLE) {
                        mRollerRecycleViewRl.setVisibility(View.VISIBLE);
                    }

                    startScroller();
                }
            } else if (Constants.HOMEPAGE_MENUMANGER.equals(intent.getAction())) {

                if (mCoverLayout.getVisibility() == View.VISIBLE) {
                    mExchangeHandler.sendEmptyMessage(HIDDERN_COVERLAYOUT_ACTION);
                    mRollerRecycleViewRl.setVisibility(View.GONE);
                }
            } else if (Constants.HOMEPAGE_MENUNEWNOTICE.equals(intent.getAction())) {


                if (mCoverLayout.getVisibility() == View.GONE) {
                    mExchangeHandler.sendEmptyMessage(SHOW_COVERLAYOUT_ACTION);
                    getHomepage();
                }

            } else if (intent.getAction().equals(Constants.RESTART_ACTION)) {
                throw new RuntimeException("定时重启");
            }


        }

    }


    /**
     * 开始滑动
     * <p>
     * 这边两个值6，2 是默认最小值
     */
    private void startScroller() {
        Log.i("text", "#####进入startScroller");
        if (mGlobalTimer != null) {
            return;
        }
        try {
            String singleTimeStr = SharedPreferencesUtils.getSharedPreferences(Constants.CONFIG_SINGLENOTICE_PEROID, HomePageActivity.this);
            String mutipleTimeStr = SharedPreferencesUtils.getSharedPreferences(Constants.CONFIG_MULTIPLENOTICE_PEROID, HomePageActivity.this);
//            singleTime = TextUtils.isEmpty(singleTimeStr) ? 6 : Double.parseDouble(singleTimeStr);

            double singleTimeD = Double.parseDouble(singleTimeStr);
            singleTime = (int) (singleTimeD * 1000);


            double mutipleTimeD = Double.parseDouble(mutipleTimeStr);
            mutipleTime = (int) (mutipleTimeD * 1000);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            singleTime = 6000;
            mutipleTime = 2000;
        }

        mGlobalTimer = new Timer();

        mGlobalTimer.schedule(new TimerTask() {
            @Override
            public void run() {
//                Log.e("caodongquan", "init       " + System.currentTimeMillis());
                if (mGlobalPos == mRealDataList.size() - 1) {
                    if (!mHandler.hasMessages(CLEAR_COVERLAYOUT_ACTION)) {

//                        if (mRealDataList.size() <= 3) {
//                            mHandler.sendEmptyMessageDelayed(CLEAR_COVERLAYOUT_ACTION, singleTime);
//                        } else {
                        mHandler.sendEmptyMessageDelayed(CLEAR_COVERLAYOUT_ACTION, (singleTime - mutipleTime));
//                        }
                    }
                } else {
//                    Log.e("caodongquan", "mGlobalTimer   " +"  "+ System.currentTimeMillis());
                    mHandler.removeMessages(CLEAR_COVERLAYOUT_ACTION);
                    Message msg = mHandler.obtainMessage();
                    msg.what = REFRESH_COVERLAYOUT_ACTION;
                    mGlobalPos += 1;
                    msg.obj = mGlobalPos;
                    mHandler.sendMessage(msg);
                }
            }
        }, mutipleTime, mutipleTime);

        Log.i("text", "#####启动mGlobalTimer");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mServiceIntent) {
//            unbindService(mConn);
//            stopService(mServiceIntent);
//            mServiceIntent = null;
        }

        if (null != receiver) {

            if (isRegisterBro) {
                unregisterReceiver(receiver);

            }
        }

        if (null != mPlayView) {
            mPlayView.stopPlayback();
            mPlayView.release();
        }

//        mExchangeHandler = null;
//        mHandler = null;
        mVideoPath = null;
        hp = null;


    }

    private void initView() {
        //主页面初始化
        initMainLayout();
        //fragment初始化
        initFragment();
        //大屏初始化
        initCoverLayout();
        //动效监听
        initAnimationListener();
    }

    /**
     * 主操作页面的初始化
     */
    private void initMainLayout() {
//        String imageUri = "";
        if (!TextUtils.isEmpty(Constants.SERVER_PORT)) {

            imageUri = "http://" + Constants.SERVER_IP + ":" + Constants.SERVER_PORT + "/";
        } else {

            imageUri = "http://" + Constants.SERVER_IP + "/";
        }

        mContentLayout = (FrameLayout) findViewById(reight_fl);
        headIv = (ImageView) findViewById(R.id.iv_head);
        nameTv = (TextView) findViewById(R.id.name_tv);
        if (null != user) {
            nameTv.setText(user.getMemberName());
            if (!isEmpty(user.getShowPic())) {
                Glide.with(this)
                        .load(imageUri + user.getShowPic())
                        .placeholder(R.mipmap.default_head).error(R.mipmap.default_head).fitCenter()
                        .transform(new GlideCircleTransform(this)).into(headIv);
            } else {
                Glide.with(this)
                        .load(imageUri + user.getComparisonPic())
                        .placeholder(R.mipmap.default_head).error(R.mipmap.default_head).fitCenter()
                        .transform(new GlideCircleTransform(this)).into(headIv);
            }
        }


        mNoticeDataRl = (CustomRadioButton) findViewById(R.id.notice_rb);
        mPlaceDataRl = (CustomRadioButton) findViewById(R.id.configue_rb);

        initRadiobuttonListener();


        homesettingIv = (ImageView) findViewById(R.id.iv_homesetting);
        homesettingIv.setOnClickListener(this);

        reightView = (RelativeLayout) findViewById(R.id.reight_rl);

        tophiddenVV = findViewById(R.id.top_hidden_vv);
        topshowVV = findViewById(R.id.top_show_vv);


        bottomhiddenVV = findViewById(R.id.bottom_hidden_vv);
        bottomshowVV = findViewById(R.id.bottom_show_vv);
//        mCoverLayoutDownBtn = (Button) findViewById(R.id.down_btn);
//        mCoverLayoutDownBtn.setOnClickListener(this);
        animation = new TranslateAnimation(0, 300, 0, 0);
        animation.setDuration(1000);//设置动画持续时间
        animation.setRepeatCount(1);//设置重复次数
        animation.setRepeatMode(Animation.REVERSE);//设置反方向执行
        animation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                //动画开始
                topshowVV.setVisibility(View.VISIBLE);
                bottomshowVV.setVisibility(View.VISIBLE);
                tophiddenVV.setVisibility(View.GONE);
                bottomhiddenVV.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {

                //动画结束
                topshowVV.setVisibility(View.GONE);
                bottomshowVV.setVisibility(View.GONE);
                tophiddenVV.setVisibility(View.VISIBLE);
                bottomhiddenVV.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        logoIv = (ImageView) findViewById(R.id.merchant_logo_iv);
        sloganTv = (TextView) findViewById(R.id.merchant_data_tv);
//        Typeface face = Typeface.createFromAsset(getAssets(), "fonts/PINGFANG-REGULAR.TTF");
//        sloganTv.setTypeface(Constants.regularface);
//        mCoverLayoutDownBtn = (Button) findViewById(R.id.down_btn);
//        mCoverLayoutUpBtn = (Button) findViewById(R.id.up_btn);

//        mCoverLayoutDownBtn.setOnClickListener(this);
//        mCoverLayoutUpBtn.setOnClickListener(this);

        mainviewTopIv = (ImageView) findViewById(R.id.mainview_top_iv);
        mainviewTopTv = (TextView) findViewById(R.id.mainview_top_tv);
        mainviewTopTv.setOnClickListener(this);
        mainSettingTv = (TextView) findViewById(R.id.cover_setting_tv);
        mainSettingTv.setOnClickListener(this);
    }


//    //设置权限
//    public void setUpAuthorityMenu() {
//        if (null != user) {
//            if (!TextUtils.isEmpty(user.getName())) {
//                sloganTv.setText(user.getName());
//                mainviewTopTv.setText(user.getName());
//            } else {
//                sloganTv.setText("场所名称");
//                mainviewTopTv.setText("场所名称");
//            }
//            if (!TextUtils.isEmpty(user.getLogo())) {
//                logoIv.setVisibility(View.VISIBLE);
//                Glide.with(this).load(Constants.HTTP_URL_IMAGESERVER + user.getLogo()).placeholder(R.drawable.device_location)
//                        .error(R.drawable.device_location).fitCenter().transform(new GlideCircleTransform(this)).into(logoIv);
//                mainviewTopIv.setVisibility(View.VISIBLE);
//                Glide.with(this).load(Constants.HTTP_URL_IMAGESERVER + user.getLogo()).placeholder(R.drawable.device_location)
//                        .error(R.drawable.device_location).fitCenter().transform(new GlideCircleTransform(this)).into(mainviewTopIv);
//
//            } else {
//
//                logoIv.setVisibility(View.GONE);
//                mainviewTopIv.setVisibility(View.GONE);
//
//            }
//
//
//        }
//    }


    /**
     * 获取首屏logo之类
     * 获取管理员通知
     */
    public void getHomepage() {

        mNoticeBackgroundPresenter = new NoticeBackgroundPresenter(this, this, 1);
        HashMap<String, Object> params = new HashMap<>();
        params.put("Authorization", mAuthtoken);
        mNoticeBackgroundPresenter.getNoticeBackground(params);


        homepagePresenter = new HomepagePresenter(this, 0);
        HashMap<String, Object> params1 = new HashMap<String, Object>();
        params1.put("Authorization", mAuthtoken);
        homepagePresenter.getHomepageRequest(params1);
    }


    public void getUser(String uuid) {
        getUserPresenter = new HomepagePresenter(this, 1);
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", mAuthtoken);
        params.put("uuid", uuid);
        getUserPresenter.getUserRequest(params);
    }


    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.iv_homesetting) {
            if (ClickTimeSpanUtil.isFastDoubleClick()) {
                return;
            }

            AboutDialog pDialog = new AboutDialog(this);
            pDialog.setDialogTitle("设置");
            pDialog.show();
        } else if (i == R.id.cover_setting_tv) {

            if (null != hp) {
                if (hp.getIsIndexConfig() == 2) {
//                    //停止播放
                    mPlayView.pause();
                    mPlayView.stopPlayback();
                    //这里必须把控件设为不可见，不然在选中照片后悔播放
                    mPlayView.setVisibility(View.GONE);
                    allVideoRl.setVisibility(View.GONE);

                }
            }
            mExchangeHandler.sendEmptyMessage(HIDDERN_COVERLAYOUT_ACTION);
        } else if (i == R.id.down_btn) {
            mExchangeHandler.sendEmptyMessage(SHOW_COVERLAYOUT_ACTION);
        } else if (i == R.id.mainview_top_tv) {
            sendBroadcast(new Intent("close_socket"));
            finish();
        } else if (i == R.id.notice_rb) {
            onRadioClickEvent(4);
        } else if (i == R.id.configue_rb) {
            onRadioClickEvent(9);
        }
    }


    /**
     * 初始化覆盖页面的相关内容以及动画
     */
    private void initCoverLayout() {
        mCoverLayout = (RelativeLayout) findViewById(R.id.coverlayout);
        mCoverContentsTv = (TextView) findViewById(R.id.mainview_content_tips_tv);
        mCoverLocNameTv = (TextView) findViewById(R.id.mainview_bottom_locname_tv);
        mCoverLocNameTv.setVisibility(View.GONE);
//        if (user == null || TextUtils.isEmpty(user.getName())) {
//            mCoverLocNameTv.setText("场所名称");
//        } else {
//            mCoverLocNameTv.setText(user.getName());
//        }
        mCoverUserNameTv = (TextView) findViewById(R.id.mainview_content_name_tv);
        mCoverHeaderIv = (ImageView) findViewById(R.id.mainview_header_bg_iv);
//        mExchangeView = (ImageView) findViewById(R.id.btn);

        mRollerRecycleViewRl = (RelativeLayout) findViewById(R.id.recyclerview_rl);
        mRollerRecycleView = (RecyclerView) findViewById(R.id.recyclerview);
        mRollerAdapter = new RollerAdapter(this, mRealDataList, new RecyclerItemClick() {
            @Override
            public void onItemClick(View view, int postion) {
                int i = view.getId();
                if (i == R.id.header_iv) {
//                    try {
//                        int lastpostion = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
//                        PushEntity pe = mRealDataList.get(postion);
//                        Intent intent = new Intent(HomePageActivity.this, OperatorMenuActivity.class);
//                        if (lastpostion == postion) {
//                            intent.putExtra("position", 2);
//                        } else if (lastpostion - 1 == postion) {
//                            intent.putExtra("position", 1);
//                        } else if (lastpostion - 2 == postion) {
//                            intent.putExtra("position", 0);
//                        }
//                        intent.putExtra("data", pe);
//                        startActivity(intent);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }

                }
            }
        });
        mLinearLayoutManager = new LinearLayoutManager(this);
        mLinearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        mRollerRecycleView.setLayoutManager(mLinearLayoutManager);

        //设置了间距 会导致滚动失败
//        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.dp_15);
//        mRollerRecycleView.addItemDecoration(new SpaceItemDecoration(spacingInPixels));
        mRollerRecycleView.setAdapter(mRollerAdapter);
        mRollerRecycleView.addOnScrollListener(mScrollListener);

        allCovRl = (RelativeLayout) findViewById(R.id.all_cov_rl);
        defaultCovll = (LinearLayout) findViewById(R.id.default_cov_ll);
        allVideoRl = (RelativeLayout) findViewById(R.id.video_cov_rl);


//        mVideoPlayView = (VlcVideoView) findViewById(R.id.video_fullscreen_view);
//        mTipView = (TextView) findViewById(R.id.video_fullscreen_tip_tv);
//        mMediaControl = new MediaControl(mVideoPlayView, mTipView, null);
//        mVideoPlayView.setMediaListenerEvent(mMediaControl);

//        videoView1 = (VideoView) findViewById(R.id.myvideoview);
//        //设置相关的监听
//        videoView1.setOnPreparedListener(this);
//        videoView1.setOnErrorListener(this);
//        videoView1.setOnCompletionListener(this);

        Log.i("test", "########初始化控件");
//        mVideoView = (io.vov.vitamio.widget.VideoView) findViewById(R.id.surface_view);
//        mVideoView.setOnPreparedListener(this);
//        mVideoView.setOnCompletionListener(this);
//        mVideoView.setOnErrorListener(this);

        mPlayView = (BDCloudVideoView) findViewById(R.id.paly);
        mPlayView.setVideoScalingMode(BDCloudVideoView.VIDEO_SCALING_MODE_SCALE_TO_MATCH_PARENT);
        mPlayView.setLooping(true);
        mPlayView.setOnCompletionListener(this);
    }


    /**
     * fragment 页面
     */
    private void initFragment() {
        fragmentManager = getSupportFragmentManager();

        mNoticeListFragment = new NoticeListFragment();
        mAddFirstScreenFragment = AddFirstScreenFragment.newInstance();

        fragmentManager.beginTransaction().replace(reight_fl, mNoticeListFragment, "noticeListFragment").addToBackStack(null).commit();
        mNoticeDataRl.setChecked(true);
    }

    /**
     * 主屏页面动画监听
     */
    private void initAnimationListener() {

        inAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                if (null == hp) {
                    allCovRl.setBackgroundDrawable(null);
                    allCovRl.setBackgroundResource(R.drawable.cover_bg);
                    defaultCovll.setVisibility(View.GONE);
                    allVideoRl.setVisibility(View.GONE);
                }
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                Log.i("test", "#####onAnimationEnd refreshCustomView");
                refreshCustomView();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        outAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mCoverLayout.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });


    }


    /**
     * 刷新界面显示方式
     */
    private void refreshCustomView() {

        if (mRealDataList.isEmpty()) {
            //这里的图片路径始终用启动时的
//            String imageUri = "";
//            if (!TextUtils.isEmpty(Constants.SERVER_PORT)) {
//
//                imageUri = "http://" + Constants.SERVER_IP + ":" + Constants.SERVER_PORT + "/";
//            } else {
//
//                imageUri = "http://" + Constants.SERVER_IP + "/";
//            }

            if (null != hp) {

                if (hp.getIsIndexConfig() == 0) {
                    //系统默认
                    Glide.with(this)
                            .load(imageUri + hp.getIndexPic())
                            .placeholder(R.drawable.mainview_default_header).error(R.drawable.mainview_default_header).centerCrop()
                            .transform(new NewGlideCircleHasBackgroudTransform(getApplicationContext(), 1, mCoverHeaderIv.getLayoutParams().width)).into(mCoverHeaderIv);
                    mCoverContentsTv.setVisibility(View.VISIBLE);
                    try {
                        mCoverContentsTv.setText(hp.getIndexBanner());
                    } catch (Exception e) {
                        mCoverContentsTv.setText("");
                    }

//                    mCoverUserNameTv.setText(user.getName());

                    allCovRl.setBackgroundDrawable(null);
                    allCovRl.setBackgroundResource(R.drawable.cover_bg);
                    defaultCovll.setVisibility(View.VISIBLE);
                    allVideoRl.setVisibility(View.GONE);


                } else if (hp.getIsIndexConfig() == 1) {
                    //图片方式
                    Glide.with(this).load(imageUri + hp.getIndexBackground()).into(new SimpleTarget<GlideDrawable>() {
                        @Override
                        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                            allCovRl.setBackgroundDrawable(resource);
                        }
                    });

                    defaultCovll.setVisibility(View.GONE);
                    allVideoRl.setVisibility(View.GONE);

                } else if (hp.getIsIndexConfig() == 2) {
                    //视频方式
                    mVideoPath = hp.getIndexBackground();
                    //播放视频
                    defaultCovll.setVisibility(View.GONE);
                    mPlayView.setVisibility(View.VISIBLE);
                    allVideoRl.setVisibility(View.VISIBLE);
                    playVideo();

                }
            } else {
                allCovRl.setBackgroundDrawable(null);
                allCovRl.setBackgroundResource(R.drawable.cover_bg);
                defaultCovll.setVisibility(View.GONE);
                allVideoRl.setVisibility(View.GONE);
            }


            user = SharedPreferencesUtils.getUserSharedPreferences(getApplicationContext());
            if (user != null) {
//                    mCoverLocNameTv.setText(user.getName());
                mCoverUserNameTv.setText(user.getName());
                if (!TextUtils.isEmpty(user.getName())) {
                    sloganTv.setText(user.getName());
                    mainviewTopTv.setText(user.getName());
                } else {
                    sloganTv.setText("场所名称");
                    mainviewTopTv.setText("场所名称");
                }
                if (!TextUtils.isEmpty(user.getLogo())) {
                    logoIv.setVisibility(View.VISIBLE);
                    Glide.with(this).load(imageUri + user.getLogo()).placeholder(R.drawable.device_location)
                            .error(R.drawable.device_location).fitCenter().transform(new GlideCircleTransform(this)).into(logoIv);
                    mainviewTopIv.setVisibility(View.VISIBLE);
                    Glide.with(this).load(imageUri + user.getLogo()).placeholder(R.drawable.device_location)
                            .error(R.drawable.device_location).fitCenter().transform(new GlideCircleTransform(this)).into(mainviewTopIv);

                } else {
                    logoIv.setVisibility(View.GONE);
                    mainviewTopIv.setVisibility(View.GONE);

                }

            }
        } else {

        }
        mContentLayout.setVisibility(View.GONE);
    }

    /**
     * 播放视频
     */
    private void playVideo() {
        Log.i("test", "#####调用playVideo");
        mHandlerExit.postDelayed(new Runnable() {
            @Override
            public void run() {
                //网络地址
//                videoView1.setVideoPath(imageUri+mVideoPath);
////                videoView1.setVideoURI(Uri.parse("http://vjs.zencdn.net/v/oceans.mp4"));
//                //开始播放
//                videoView1.start();

//                String imageUri = "";
//                if (!TextUtils.isEmpty(Constants.SERVER_PORT)) {
//
//                    imageUri = "http://" + Constants.SERVER_IP + ":" + Constants.SERVER_PORT + "/";
//                } else {
//
//                    imageUri = "http://" + Constants.SERVER_IP + "/";
//                }


                if (mRealDataList.isEmpty()) {
                    //开始播放
                    if (!mPlayView.isPlaying()) {
                        mPlayView.setVideoPath(imageUri + mVideoPath);
                        mPlayView.start();
                    }

//                    mVideoView.setVideoPath(imageUri +mVideoPath);
//                   //不显示进度条
//            mVideoView.setMediaController(new MediaController(this));
//                    mVideoView.requestFocus();
                }


            }
        }, 100);
    }


    /**
     * 暂停播放
     */
    public void pausePaly() {
        Log.i("test", "#####暂停播放");
//        if(mVideoView.isPlaying())
//        {
//        mVideoView.pause();
//        }

        if (mPlayView.canPause()) {
            mPlayView.pause();
        }
    }

    /**
     * 恢复播放
     */
    public void resumePaly() {
        Log.i("test", "#####恢复播放");
//        mVideoView.start();

        mPlayView.start();

    }


    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case SCROLLER_END_ACTION:  //这个是手指滑动结束后发送的事件
                    try {
                        int stoppos = (int) msg.obj;
                        //避免数组越界的问题
                        if (mRealDataList.isEmpty() || (mRealDataList.size() < stoppos)) {
                            return;
                        }
//                        PushEntity pushEntity = mRealDataList.get(stoppos);
//                        if (pushEntity.getAlarmState() != 3) {
//                            updateCoverView(pushEntity);
//                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                case REFRESH_COVERLAYOUT_ACTION:

                    try {
                        int pos = (int) msg.obj;
                        //避免数组越界的问题
                        if (mRealDataList.isEmpty() || (mRealDataList.size() < pos)) {
                            return;
                        }
//                        PushEntity pe = mRealDataList.get(pos);

                        sendEmptyMessage(RECYCLERVIEW_SCOLLER_ACTION);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case CLEAR_COVERLAYOUT_ACTION:
                    mGlobalPos = 0;
                    mRealDataList.clear();
                    mRollerAdapter.notifyDataSetChanged();
                    if (mGlobalTimer != null) {
                        mGlobalTimer.cancel();
                        mGlobalTimer = null;
                    }
                    playYetPos = 0;
                    mRollerRecycleViewRl.setVisibility(View.GONE);
                    PlaySoundUtils.releaseMedia();

                    if (null != hp) {
                        if (hp.getIsIndexConfig() == 2) {
                            //播放视频
                            defaultCovll.setVisibility(View.GONE);
                            mPlayView.setVisibility(View.VISIBLE);
                            allVideoRl.setVisibility(View.VISIBLE);
                            //恢复播放
                            resumePaly();
                        }
                    }


//                    //刷新默认界面
//                    refreshCustomView();


                    break;
                case RECYCLERVIEW_SCOLLER_ACTION:
                    try {
                        if (mGlobalPos < mRealDataList.size()) {
                            int pos = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
                            int right = mLinearLayoutManager.findViewByPosition(pos).getRight();
                            int size = CommonUtils.getScreenWidth(HomePageActivity.this);
                            int offset = 0;
                            if (size - 1 > right) {
                                offset = size - 1 - right;
                            }
//                            Log.e("caodongquan", "RECYCLERVIEW_SCOLLER_ACTION       " + System.currentTimeMillis());
                            mRollerRecycleView.smoothScrollBy((CommonUtils.getScreenWidth(HomePageActivity.this) / 3) - offset, 0);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

            }
        }

    };


    @Override
    public void setPresenter(BasePresenter tp) {

    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }


    /**
     * 停止后重新开始计时，滚动
     */
    private void restartScroll() {

        if (mRealDataList.isEmpty()) {
            return;
        }
        if (flyByFinger) {
            try {
                mGlobalPos = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
                Message msg = mHandler.obtainMessage();
                msg.what = SCROLLER_END_ACTION;
                msg.obj = mGlobalPos;
                mHandler.sendMessage(msg);

                if (mHandler.hasMessages(CLEAR_COVERLAYOUT_ACTION)) {
                    mHandler.removeMessages(CLEAR_COVERLAYOUT_ACTION);
                }
                startScroller();
            } catch (Exception e) {
                e.printStackTrace();
                flyByFinger = false;
            }
            flyByFinger = false;
        }
    }


    @Override
    public void onBackPressed() {
        try {
            int size = getSupportFragmentManager().getBackStackEntryCount();
            if (size > 0) {
                String tag = getSupportFragmentManager().getBackStackEntryAt(size - 1).getName();
                Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(tag);
                if (currentFragment != null) {
                    FragmentManager childFragmentManager = currentFragment.getChildFragmentManager();
                    if (childFragmentManager.getBackStackEntryCount() > 0) {

                        int childSize = childFragmentManager.getBackStackEntryCount();

                        if (childSize == 1) {
                            String subTag = getSupportFragmentManager().getBackStackEntryAt(1).getName();
                            childFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);//清空子fragment堆栈中的所有fragment

                            if ("patrolListFragment".equals(subTag) || "frequencyFragment".equals(subTag)) {
                                getSupportFragmentManager().popBackStack(subTag, 0);
                            } else {
                                getSupportFragmentManager().popBackStack(subTag, FragmentManager.POP_BACK_STACK_INCLUSIVE);//清空父fragment堆栈中，自身及以上的所有fragment
                            }
                        } else {
                            childFragmentManager.popBackStack();
                        }
                    } else {
                        getSupportFragmentManager().popBackStack();
                    }
                } else {
                    exit();
                }
            } else {
                exit();
            }
        } catch (Exception e) {
            e.printStackTrace();
            exit();
        }
    }

    public void exit() {
//        try {
//            mIntelCameraApplication.clearAllList();
//            sendBroadcast(new Intent("close_service"));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        Intent intent = new Intent(HomePageActivity.this, PlaceInfoListActivity.class);
//        intent.putExtra("from", "homepage");
//        startActivity(intent);


        sendBroadcast(new Intent("close_socket"));
        finish();
    }


    private Executor executor = Executors.newCachedThreadPool();

    private void playSoundByType(PushEntity pe) {

        executor.execute(new PlaySoundRunnable(pe));

//        String uuid = pe.getNotificationUuid();
//        LocNoticeInfo info = DBManager.getInstance(this).findLocNoticeInfoByUuid(uuid);
//        if (null != info) {
//            Log.i(Constants.TAG, "###通知铃声类型：" + info.getSoundType());
//            if (info.getSoundType() == 0) {
//                switch (pe.getIsStranger()) {
//                    case 0:
//
//                        switch (pe.getAlarmState()) {
//                            case 1:
//                                PlaySoundUtils.playLocalSound(HomePageActivity.this, 0);
////                                playSound(HomePageActivity.this, 0);
//                                break;
//                            case 0:
//                                PlaySoundUtils.playLocalSound(HomePageActivity.this, 1);
////                                playSound(HomePageActivity.this, 1);
//                                break;
//                        }
//                        break;
//                    case 1:
//                        PlaySoundUtils.playLocalSound(HomePageActivity.this, 2);
////                        playSound(HomePageActivity.this, 2);
//                        break;
//                }
//
//            } else {
//                if (!TextUtils.isEmpty(info.getSoundUrl())) {
//                    File file = new File(info.getSoundUrl());
//                    if (file.exists()) {
//                        PlaySoundUtils.playSoundUrl(info.getSoundUrl());
////                        playSoundUrl(this, info.getSoundUrl(), (mRealDataList.indexOf(pe) == mRealDataList.size() - 1));
//                    }
//                }
//
//            }
//        } else {
//            switch (pe.getIsStranger()) {
//                case 0:
//
//                    switch (pe.getAlarmState()) {
//                        case 1:
//                            PlaySoundUtils.playLocalSound(HomePageActivity.this, 0);
////                            playSound(HomePageActivity.this, 0);
//                            break;
//                        case 0:
//                            PlaySoundUtils.playLocalSound(HomePageActivity.this, 1);
////                            playSound(HomePageActivity.this, 1);
//                            break;
//                    }
//                    break;
//                case 1:
//                    PlaySoundUtils.playLocalSound(HomePageActivity.this, 2);
////                    playSound(HomePageActivity.this, 2);
//                    break;
//            }
//
//
//        }
    }


    private class PlaySoundRunnable implements Runnable {

        PushEntity pe;
        String packagename;

        public PlaySoundRunnable(PushEntity pushEntity) {
            pe = pushEntity;
            packagename = getApplicationContext().getPackageName();
        }

        @Override
        public void run() {


            String uuid = pe.getNotificationUuid();
            LocNoticeInfo info = DBManager.getInstance(getApplicationContext()).findLocNoticeInfoByUuid(uuid);

            MediaPlayer mediaPlayer = new MediaPlayer();

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                    mp = null;
                }
            });
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    mp = null;
                    return false;
                }
            });
            Uri uri;
            if (null != info) {
//                Log.i(Constants.TAG, "###通知铃声类型：" + info.getSoundType());
                if (info.getSoundType() == 0) {
                    switch (pe.getIsStranger()) {
                        case 0:

                            switch (pe.getAlarmState()) {
                                case 1:
//                                    PlaySoundUtils.playLocalSound(HomePageActivity.this, 0);
                                    try {
                                        uri = Uri.parse("android.resource://" + packagename + "/" + R.raw.danger);
                                        mediaPlayer.setDataSource(getApplicationContext(), uri);
                                        mediaPlayer.prepare();
                                        mediaPlayer.start();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    break;
                                case 0:
                                    try {
                                        uri = Uri.parse("android.resource://" + packagename + "/" + R.raw.normal);
                                        mediaPlayer.setDataSource(getApplicationContext(), uri);
                                        mediaPlayer.prepare();
                                        mediaPlayer.start();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    break;
                            }
                            break;
                        case 1:
                            try {
                                uri = Uri.parse("android.resource://" + packagename + "/" + R.raw.stranger);
                                mediaPlayer.setDataSource(getApplicationContext(), uri);
                                mediaPlayer.prepare();
                                mediaPlayer.start();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            break;
                    }

                } else {
                    if (!TextUtils.isEmpty(info.getSoundUrl())) {
                        File file = new File(info.getSoundUrl());
                        if (file.exists()) {
                            PlaySoundUtils.playSoundUrl(info.getSoundUrl());
                            try {
                                mediaPlayer.setDataSource(info.getSoundUrl());
                                mediaPlayer.prepare();
                                mediaPlayer.start();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
            } else {
                switch (pe.getIsStranger()) {
                    case 0:

                        switch (pe.getAlarmState()) {
                            case 1:
                                try {
                                    uri = Uri.parse("android.resource://" + packagename + "/" + R.raw.danger);
                                    mediaPlayer.setDataSource(getApplicationContext(), uri);
                                    mediaPlayer.prepare();
                                    mediaPlayer.start();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                break;
                            case 0:
                                try {
                                    uri = Uri.parse("android.resource://" + packagename + "/" + R.raw.normal);
                                    mediaPlayer.setDataSource(getApplicationContext(), uri);
                                    mediaPlayer.prepare();
                                    mediaPlayer.start();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                break;
                        }
                        break;
                    case 1:
                        try {
                            uri = Uri.parse("android.resource://" + packagename + "/" + R.raw.stranger);
                            mediaPlayer.setDataSource(getApplicationContext(), uri);
                            mediaPlayer.prepare();
                            mediaPlayer.start();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                }


            }


        }
    }

    /**
     * radio button 监听 设置
     */
    private void initRadiobuttonListener() {

        mNoticeDataRl.setOnClickListener(this);

        mPlaceDataRl.setOnClickListener(this);

    }


    /**
     * @param type 0 设备
     *             1 人员
     *             2 未登记
     *             3 访客
     *             4 通知
     *             5 统计
     *             6 系统
     *             7 智能门岗
     *             8 数据统计
     *             9 配置
     *             10 报表
     *             11 账户管理
     */
    private void onRadioClickEvent(int type) {
        fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        switch (type) {


            case 4:
                mNoticeListFragment = new NoticeListFragment();
                getSupportFragmentManager().beginTransaction().replace(R.id.reight_fl, mNoticeListFragment, "noticeListFragment").addToBackStack(null).commitAllowingStateLoss();
                break;

            case 9:
                mAddFirstScreenFragment = (AddFirstScreenFragment) getSupportFragmentManager().findFragmentByTag("addFirstScreenFragment");
                if (mAddFirstScreenFragment == null) {
                    mAddFirstScreenFragment = mAddFirstScreenFragment.newInstance();
                }
                getSupportFragmentManager().beginTransaction().replace(R.id.reight_fl, mAddFirstScreenFragment, "addFirstScreenFragment").addToBackStack(null).commitAllowingStateLoss();
                break;

        }
        reightView.setAnimation(animation);
        animation.startNow();
    }


    private String uuid, placeInfoName, placeInfoLogo, /*httpUrlHeader, httpUrlImageServer,*/
            socketIp, socketPort, partitionUuid, placename, communityUuid, phone, serverIp, serverPort;
    private int controlTime;
    boolean isOnline = false;
    private HomePageConfigure hp;

    private NoticeBackground nb;

    private void initParam() {

        Intent intent = getIntent();
        //获取该intent所携带的数据
        if (null != intent) {
            Bundle data = intent.getExtras();
            if (null != data) {

                mAuthtoken = data.getString("authtoken");
                uuid = data.getString("uuid");
                placeInfoName = data.getString("placeInfoName");
                placeInfoLogo = data.getString("placeInfoLogo");
                partitionUuid = data.getString("partitionUuid");
                placename = data.getString("placename");
                communityUuid = data.getString("communityUuid");
                controlTime = data.getInt("controlTime", 0);

                phone = data.getString("phone");
                socketIp = data.getString("socketip");
                socketPort = data.getString("socketport");
                isOnline = data.getBoolean("isonline_version", false);
                serverIp = data.getString("server_ip");
                serverPort = data.getString("server_port");
                Constants.SERVER_IP = serverIp;
                Constants.SERVER_PORT = serverPort;
                Constants.refreshIP();
//                httpUrlHeader = data.getString("httpUrl");
//                httpUrlImageServer = data.getString("httpUrlImageServer");
//                Constants.HTTP_URL_HEADER = httpUrlHeader;
//                Constants.HTTP_URL_IMAGESERVER = httpUrlImageServer;

//                Constants.SERVER_IP = data.getString("server_ip");
//                Constants.SERVER_PORT = data.getString("server_port");
//                Constants.refreshIP();


                Constants.ISONLINE_VERSION = isOnline;
//                    SharedPreferencesUtils.setBooleanSharedPreferences("isonline_version", isOnline, getApplicationContext());
                Constants.NOTICE_SERVER_IP = socketIp;
                Constants.NOTICE_SERVER_PORT = socketPort;
                Param p = new Param();
                p.mAuthtoken = mAuthtoken;
                p.uuid = uuid;
                p.placeInfoName = placeInfoName;
                p.placeInfoLogo = placeInfoLogo;
                p.serverIp = serverIp;
                p.serverPort = serverPort;
                p.communityUuid = communityUuid;
                p.partitionUuid = partitionUuid;
                p.phone = phone;
                p.socketIp = socketIp;
                p.socketPort = socketPort;
                p.controlTime = controlTime;
                SharedPreferencesUtils.setParamSharedPreferences(p, getApplicationContext());
                if (!TextUtils.isEmpty(mAuthtoken) && !TextUtils.isEmpty(mAuthtoken)) {
                    //获取用户信息
                    SharedPreferencesUtils.setSharedPreferences(Constants.CONFIG_PLACE_AUTHTOKEN, mAuthtoken, this);
                    SharedPreferencesUtils.setSharedPreferences(Constants.CONFIG_AUTHTOKEN, mAuthtoken, this);
                } else {
                    finish();
                }
            } else {
                finish();
            }
        } else {
            finish();

        }

    }

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

            if (parent.getChildPosition(view) != 0)
//                outRect.left = space;
                outRect.left = space;
            outRect.right = getResources().getDimensionPixelSize(R.dimen.dp_3);
        }
    }

    private void startService() {
        Intent monitorIntent = new Intent(this, IntelligenceBackService.class);
        monitorIntent.putExtra("socketip", socketIp);
        monitorIntent.putExtra("socketport", socketPort);
        monitorIntent.putExtra("phone", phone);
        monitorIntent.putExtra("partitionUuid", partitionUuid);
//        monitorIntent.putExtra("type", "1");
        startService(monitorIntent);
    }

    public void startTask() {
        pendingIntent = PendingIntent.getService(this, 10000, new Intent(this, AuthtokenIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManger = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManger.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),/* 60 * 2 * 60*/60 * 60 * 1000, pendingIntent);
    }
}